#include "widget.h"
#include "ui_widget.h"
#include <QPixmap>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    client = new QTcpSocket(this);
    QObject::connect(client, &QTcpSocket::readyRead, this, &Widget::onReadyRead);
    ui->pushButton->setEnabled(false);
    ui->pushButton_2->setEnabled(false);
    QObject::connect(ui->lineEdit,&QLineEdit::textChanged,this,&Widget::checkInput);
    QObject::connect(ui->lineEdit_2,&QLineEdit::textChanged,this,&Widget::checkInput);

    // 关键：强制启用工具提示，即使按钮处于禁用状态
    //ui->pushButton->setAttribute(Qt::WA_AlwaysShowToolTips);
    //ui->pushButton_2->setAttribute(Qt::WA_AlwaysShowToolTips);

    //checkInput();

    userinterface = new Userinterface;
    userinterface->setLoginInterface(this);
    userinterface->setClient(client);
    QFile file(":/LoginWidget.qss");
    if(file.open(QFile::OpenModeFlag::ReadOnly)){
        this->setStyleSheet(file.readAll());
    }
    QPixmap pixmap(":/logo.PNG");
    if(!pixmap.isNull()){
        //调整图片大小
        QPixmap scaledPixmap=pixmap.scaled(ui->label_2->size(),
                                           Qt::KeepAspectRatio,
                                           Qt::SmoothTransformation);
        ui->label_2->setPixmap(scaledPixmap);
        ui->label_2->setAlignment(Qt::AlignCenter);
    }
    isAgreed = false;
        checkInput();
}

Widget::~Widget()
{
    delete ui;
}

// 注册按钮点击事件（widget.cpp中）
QPixmap Widget::byteArr2Pic(QByteArray &arr)
{
    QBuffer buf(&arr);
    QImageReader reader(&buf,"jpg");
    QImage image = reader.read();
    return QPixmap::fromImage(image);
}
void Widget::on_pushButton_clicked()
{
    // 检查当前socket状态，仅在未连接时发起连接
    if (client->state() != QTcpSocket::ConnectedState) {
        ip.setAddress(ui->lineEdit_3->text());
        port = ui->lineEdit_4->text().toInt();
        client->connectToHost(ip, port);

        // 等待连接结果（超时2秒）
        if (!client->waitForConnected(2000)) {
            QMessageBox::warning(this, "连接", "连接失败，请检查网络");
            return;
        }
    }

    // 连接成功后发送注册数据
    QString name = ui->lineEdit->text();
    QString pswd = ui->lineEdit_2->text();
    Pack pack;

    pack.setType(TYPE_REGIST);
    pack << name << pswd;
    pack >> client;
}

// 登录按钮点击事件（widget.cpp中）
void Widget::on_pushButton_2_clicked()
{
    // 检查当前socket状态，仅在未连接时发起连接
    if (client->state() != QTcpSocket::ConnectedState) {
        ip.setAddress(ui->lineEdit_3->text());
        port = ui->lineEdit_4->text().toInt();
        client->connectToHost(ip, port);

        // 等待连接结果（超时2秒）
        if (!client->waitForConnected(2000)) {
            QMessageBox::warning(this, "连接", "连接失败，请检查网络");
            return;
        }
    }

    // 连接成功后发送登录数据
    QString name = ui->lineEdit->text();
    QString pswd = ui->lineEdit_2->text();
    currentUsername = name; // 保存当前用户名（新增）
               userinterface->setcurrentUsername(name);
    Pack pack;

    pack.setType(TYPE_LOGIN);
    pack << name << pswd;
    pack >> client;
}

// 连接服务器
void Widget::on_pushButton_3_clicked()
{
    ip.setAddress(ui->lineEdit_3->text());
    port = ui->lineEdit_4->text().toInt();
    client->connectToHost(ip,port);
    if(client->waitForConnected(2000)){
        //如果2秒内连接上服务器
        QMessageBox::information(this,"连接","连接服务器成功");
    }else{
        QMessageBox::warning(this,"连接","连接失败，请检查网络");
    }
}

// 服务器向客户端发送数据的时候，会自动触发的一个函数
// 在onReadyRead函数的switch中补充default分支
void Widget::onReadyRead()
{
    while(client->bytesAvailable()) {
        int res = 0;
        int size = 0;
        Pack pack;



        if(unreaded_pack_size != 0){
            res = client->read((char*)&readed_pack + readed_pack_size,unreaded_pack_size);
            if(res != unreaded_pack_size){
                // 这里只要更新下已读大小和未读大小，保证下一次进入当前分支的时候，能够根据已读大小和未读大小，读取对应的数据以及存放到对应的地方
                readed_pack_size += res;
                unreaded_pack_size -= res;
                break;
            }

            pack = readed_pack;
            // 处理完分包记得 unreaded_pack_size = 0;
            unreaded_pack_size = 0;
        }else{

            if(unreaded_size_size != 0){
                client->read((char*)&readed_size + readed_size_size,unreaded_size_size);
                size = readed_size;
                unreaded_size_size = 0;
            }else{

                // else 部分为正常读取数据：先读4字节，再读剩余字节数，可能处理分包
                res = client->read((char*)&size,4);
                if(res == 0){break;}

                if(res != 4){
                    readed_size = size;
                    readed_size_size = res;
                    unreaded_size_size = 4 - res;
                    break;
                }
            }


            res = client->read((char*)&pack+4,size-4);
            if(res == 0){break;}

            pack.setSize(size);


            if(res != size-4){
                // 如果实际读取到的字节数 != 想要读取的字节数
                // 说明发生了分包
                readed_pack = pack;// 将已经读取的协议包缓存在每个客户端专属的缓存区 readed_pack 里面
                readed_pack_size = res + 4;
                unreaded_pack_size = size - readed_pack_size;
                break;
            }
        }
        // 路由数据包
        switch(pack.getType()) {
            case TYPE_REGIST:
            case TYPE_LOGIN:
                // 处理登录/注册响应
                handleLoginResponse(pack);
                break;



            case TYPE_SCHEDULE_SAVE:
            case TYPE_SCHEDULE_UPDATE:
            case TYPE_SCHEDULE_DELETE:
            case TYPE_SCHEDULE_QUERY:
            case TYPE_SCHEDULE_QUERY_ALL:
                // 转发给schedule界面处理
                if(userschedule) {
                    userschedule->handleScheduleResponse(pack);
                }
                break;
            case TYPE_ONLINE_LIST:
                // 转发给myMessage窗口处理在线列表
                if (userinterface && userinterface->getMyMessage()) {
                    userinterface->getMyMessage()->handleOnlineList(pack);
                }
            case TYPE_MESSAGE:
            {
                QList<QString> list = pack.readAll();
                if (list.size() == 4) {
                    QString sender = list[0];
                    QString receiver = list[1];
                    QString msg = list[2];
                    QString time = list[3];
            
                    qDebug() << "收到消息：" << sender << "->" << receiver << ":" << msg << "(" << time << ")";
            
                    // 检查是否是发给当前用户的消息
                    if (receiver == currentUsername || receiver == "all") {
                        // 显示消息
                        userinterface->getMyMessage()->showReceivedMessage(sender, msg, time);
                    }
                } else if (list.size() == 1 && list[0] == BACK_SUCCESS) {
                    qDebug() << "消息发送成功";
                } else {
                    qDebug() << "无效的消息包结构，列表大小：" << list.size();
                }
                break;
            }
        case TYPE_TEXT:{
            QList<QString> list = pack.readAll();

            QString sender = list[0];
            QString receiver = list[1];
            QString text = list[2];


            qDebug() << "收到消息：" << sender << "->" << receiver << ":" << text;
            userinterface->textshow(sender,text);


        }
        case TYPE_SENDING_CAMERA:{
                        part_camera_pic += pack.readAll(pack.size() - 12);
                        break;
        }
                    case TYPE_SEND_CAMERA_END:{
                        part_camera_pic += pack.readAll(pack.size() - 12);
                        // 到此为止 part_camera_pic 里面拥有了一张完整的图片
                        QPixmap pic = byteArr2Pic(part_camera_pic); // 转换成QPixmap
                        userinterface->setCamerPic(pic);
                        part_camera_pic.clear();// 清理 part_camera_pic 里面的内容，以免对下一帧图片造成影响
                        break;
        }
                    // 处理桌面共享视频数据
        case TYPE_SENDING_DESKTOP:{
                   part_camera_pic += pack.readAll(pack.size() - 12); // 使用 part_camera_pic 拼接读取到的部分图片
                   break;
               }
               case TYPE_SEND_DESKTOP_END:{
                   part_camera_pic += pack.readAll(pack.size() - 12);
                   // 到此为止 part_camera_pic 里面拥有了一张完整的图片
                   QPixmap pic = byteArr2Pic(part_camera_pic); // 转换成QPixmap
                   userinterface->setDeskPic(pic);
                   part_camera_pic.clear();// 清理 part_camera_pic 里面的内容，以免对下一帧图片造成影响
                   break;

               // 在这里，新写2个case，用来接受服务器转发过来的桌面图片，并在userinterface的 label_2上面显示
               }

           case TYPE_MESSAGE_ACK: {
                // 处理发送成功/失败的确认（不显示，仅日志或提示）
                QStringList ackData = pack.readAll();
                if (pack.getBack() == BACK_ERR) {
                    QMessageBox::warning(this, "发送失败", ackData[0]);
                }
                break;
            }
            default:
                // 处理所有未明确列出的枚举值
                qDebug() << "Unhandled packet type:" << pack.getType();
        }
    }
}

void Widget::handleLoginResponse(const Pack& pack)
{
    switch(pack.getType()) {
        case TYPE_REGIST:{
            if(pack.getBack() == BACK_SUCCESS){
                QMessageBox::information(this,"注册","注册成功");
            }else{
                QMessageBox::critical(this,"注册","该账号已存在");
            }
            break;
        }
    case TYPE_LOGIN:{
        if(pack.getBack() == BACK_SUCCESS){
            QMessageBox::information(this,"登录","登录成功");

            Pack onlinePack;
           onlinePack.setType(TYPE_USER_ONLINE);
           onlinePack << currentUsername; // 发送当前登录用户名

           onlinePack >> client;
            // 初始化schedule界面
            userschedule = new schedule();
            userschedule->setSocket(client);
            userinterface->getnum(num);
            userinterface->setSchedule(userschedule);

            // +++ 新增：初始化消息窗口 +++
            myMessage* msgWindow = new myMessage();
            msgWindow->setSocket(client);
            msgWindow->setCurrentUsername(currentUsername); // 新增：设置当前用户名
            qDebug() << "初始化消息窗口，当前用户名：" << currentUsername;
            userinterface->setMyMessage(msgWindow); // 关键：将新窗口设置到userinterface中
            if (userinterface->getMyMessage() == nullptr) {
                qDebug() << "消息窗口设置失败";
            } else {
                userinterface->getMyMessage()->setSocket(client); // 确保设置socket
            }

            userinterface->show();
            this->hide();
        }else{
            QMessageBox::critical(this,"登录","账号或密码错误");
        }
        break;
    }
    }
}

void Widget::checkInput()
{
    bool hasUsername = !ui->lineEdit->text().isEmpty();
    bool hasPassword = !ui->lineEdit_2->text().isEmpty();
    bool canEnable = hasUsername && hasPassword && isAgreed; // 新增协议条件

    // 控制按钮启用状态
    ui->pushButton->setEnabled(canEnable);   // 注册按钮
    ui->pushButton_2->setEnabled(canEnable); // 登录按钮

    // 动态提示（可选，根据需求调整）
    if (!canEnable) {
        QString tip;
        if (!hasUsername)      tip = "请输入用户名";
        else if (!hasPassword) tip = "请输入密码";
        else                   tip = "请勾选服务协议"; // 协议未勾选时提示

        ui->pushButton->setToolTip(tip);
        ui->pushButton_2->setToolTip(tip);
    } else {
        ui->pushButton->setToolTip("");
        ui->pushButton_2->setToolTip("");
    }
}



void Widget::on_pushButton_5_clicked()
{
    num=1;

}


void Widget::on_pushButton_4_clicked()
{
    num=0;
}

void Widget::on_checkBox_clicked()
{
    isAgreed = ui->checkBox->isChecked(); // 更新协议状态
    checkInput(); // 重新校验输入条件

}
